package com.gitee.demo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.List;
import java.util.Map;

/**
 * AES对称加密和解密
 */
public class AESUtils {

    private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);

    /**
     * 使用AES-128-CBC加密模式，key需要为16位,key和iv可以相同！
     */
    private static String KEY = "dbapp@anheng2018";
    private static String IV = "dbapp@anheng2018";


    /**
     * 加密方法
     *
     * @param data 要加密的数据
     * @param key  加密key
     * @param iv   加密iv
     * @return 加密的结果
     */
    public static String encrypt(String data, String key, String iv) {
        try {
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encrypted = cipher.doFinal(plaintext);

            return new Base64().encodeToString(encrypted);

        } catch (Exception e) {
            logger.info("encrypt error", e);
        }
        return null;
    }

    /**
     * 解密方法
     *
     * @param data 要解密的数据
     * @param key  解密key
     * @param iv   解密iv
     * @return 解密的结果
     */
    public static String desEncrypt(String data, String key, String iv) {
        try {
            byte[] encrypted1 = new Base64().decode(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            logger.info("decrypt error", e);
        }
        return null;
    }

    /**
     * 使用默认的key和iv加密
     */
    public static String encrypt(String data) {
        return encrypt(data, KEY, IV);
    }

    /**
     * 使用默认的key和iv解密
     */
    public static String desEncrypt(String data) {
        return desEncrypt(data, KEY, IV);
    }


    /**
     * 仅仅用于 解析 防护服务登录返回值中的 token
     *
     * @param object
     * @return
     */
    public static String parseToken(Object object) {

        if (null == object) {
            return null;
        }

        try {
            JSONObject resultJSON = JSON.parseObject(JSON.toJSONString(object));
            Object data = resultJSON.get("data");
            JSONObject dataJSON = JSON.parseObject(JSON.toJSONString(data));
            Object token = dataJSON.get("token");
            return token.toString();
        } catch (Throwable e) {
            return null;
        }
    }


    /**
     * 仅仅用于 解析 扫描任务列表返回值中的 token
     *
     * @param object
     * @return
     */
    public static String parseRecord(Object object) {

        if (null == object) {
            return null;
        }

        try {
            JSONObject resultJSON = JSON.parseObject(JSON.toJSONString(object));
            Object data = resultJSON.get("data");
            JSONObject dataJSON = JSON.parseObject(JSON.toJSONString(data));
            Object records = dataJSON.get("records");

            List<Object> recordsList = JSON.parseArray(JSON.toJSONString(records), Object.class);

            Object record = recordsList.get(0);
            JSONObject recordJSON = JSON.parseObject(JSON.toJSONString(record));

            Object scanTaskHistoryInfos = recordJSON.get("scanTaskHistoryInfos");
            List<Object> scanTaskHistoryInfosList = JSON.parseArray(JSON.toJSONString(scanTaskHistoryInfos), Object.class);

            Object lastElement = ListUtil.getLastElement(scanTaskHistoryInfosList);
            JSONObject lastElementJSON = JSON.parseObject(JSON.toJSONString(lastElement));

            Object createTime = lastElementJSON.get("createTime");
            Object message = lastElementJSON.get("message");

            return createTime.toString();
        } catch (Throwable e) {
            return null;
        }
    }

}
